# coding: UTF-8
import traceback
from json.encoder import JSONEncoder
from urllib.parse import quote

from flask import make_response
from json import dumps
from functools import wraps
from core.base_error import BaseError
from datetime import datetime,date
from core.base_vo import BaseVo


class JsonEncoder(JSONEncoder):
    """自定义序列化json数据"""

    def default(self, o):
        if isinstance(o, datetime):
            return o.strftime("%Y-%m-%d %H:%M:%S")
        if isinstance(o, date):
            return o.strftime("%Y-%m-%d")
        if isinstance(o, BaseVo):
            return o.change_to_json()
        return JSONEncoder.default(self, o)


class OutputHttpResponse:
    @classmethod
    def server_error(cls):
        return output(code=10000, msg='服务器暂时无法响应，请重试~')

    @classmethod
    def args_miss_error(cls):
        return output(code=10002, msg="参数缺失~")

    @classmethod
    def args_error_error(cls):
        return output(code=10003, msg="参数错误~")

    @classmethod
    def need_login_error(cls):
        return output(code=10004, msg='您还没登录哟~')

    @classmethod
    def ok(cls, data=None):
        return output(data, code=0, msg='ok')


def output(data=None, code=0, msg='ok'):
    response = make_response(dumps({
        'code': code,
        'msg': msg,
        'data': data,
    }, cls=JsonEncoder))
    response.headers['Content-Type'] = 'application/json'
    return response


def catch_api_error(fn):
    """捕捉接口的自定义错误转成标志输出"""

    @wraps(fn)
    def handle(*k, **v):
        try:
            return fn(*k, **v)
        except BaseError as err:
            if err.http_show_msg:
                msg = err.http_show_msg
            else:
                msg = err.http_return_msg
            print(str(err) + "\n" + traceback.format_exc())
            # err_msg_test=(str(err) + '\n' + traceback.format_exc())
            return output(code=err.error_code, msg=msg)

    return handle
